//
//  QuestionViewController.swift
//  DriverSchoolAPP
//
//  Created by Logel on 2017/5/11.
//  Copyright © 2017年 Logel. All rights reserved.
//

import UIKit

class QuestionViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,LgCallBack {
    var qst = Question()
    var qtype = 0
    var errorCount = 0
    var historys = [String]()
    var clickNum = 1
    var isShow = false
    var conformBtn = UIBarButtonItem()
    var classification = ""
    
    @IBOutlet weak var tbv: UITableView!
    
    @IBOutlet weak var tnLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        tbv.tableFooterView = UIView()
        if qtype == 4 {
            isCounting = true
        }
        getData()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return qst.options.count
        default:
            if isShow{
                return 1
            }else{
                return 0
            }
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell")
        cell?.textLabel?.font = UIFont.systemFont(ofSize: 13)
        switch indexPath.section {
        case 0:
            cell?.textLabel?.numberOfLines = 0
            cell?.textLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping  //自动折行
            cell?.textLabel?.text = qst.options[indexPath.row]
        default:
            cell?.textLabel?.numberOfLines = 0
            cell?.textLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping  //自动折行
            cell?.textLabel?.text = "答案：\(qst.answer)\n解释：\( qst.explains)"
            
        }
       // cell?.textLabel?.text = "第\(indexPath.section)组,第\(indexPath.row)行"
        return cell!
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let hCell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! QustionHeaderTableViewCell
        switch section {
        case 0:
            hCell.questLbl.text = "问题：\(qst.question)"
            
            if qst.pic != "" {
                let img = getImageWithUrl(url: qst.pic)
                hCell.imgV.image = img
            }
        default:
             break
        }
        return hCell
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 205
        default:
            return 40
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            return 44
        default:
            return 140
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch qst.answer {
        case "A":
            if indexPath.row == 0 {
                 clickNum += 1
                getData()
            }else {
                toPostError()
            }
        case "B":
            if indexPath.row == 1 {
                clickNum += 1
                getData()
            }else {
                toPostError()
            }
        case "C":
            if indexPath.row == 2 {
                clickNum += 1
                getData()
            }else {
                toPostError()
            }
        case "D":
            if indexPath.row == 3 {
                clickNum += 1
                getData()
            }else {
                toPostError()
            }
        default:
            clickNum += 1
            getData()
        }
    }
    
    func toPostError() {
        asyn_req_post(method: M_SaveError, cb: self, p: ["logId":qst.logId as AnyObject])
    }
    
    func getData(){
        isShow = false
        if clickNum > historys.count {
            asyn_req_post(method: M_Question_Get, cb: self, p: ["type":qtype as AnyObject,"accountId":user.accountId as AnyObject,"testId":qst.testId as AnyObject,"logId":qst.logId as AnyObject,"classification":classification as AnyObject])
        }else{
            if historys.count>0 {
                asyn_req_post(method: M_Question_Get, cb: self, p: ["type":"5" as AnyObject,"accountId":user.accountId as AnyObject,"testId":qst.testId as AnyObject,"logId":historys[clickNum - 1] as AnyObject,"classification":classification as AnyObject])
            }else{
                showMsg(msg: "已经是第一题了")
            }

        }
        
        
    }
    
    func callBack(method: String, data: AnyObject) {
        let j = JSON(data)
        print(j)
        let head = parseMobileHead(x: j["MobileHead"])
        if head.code == "1" {
            switch method {
            case M_Question_Get:
                qst = parseQuestion(x: j["MobileBody"])
                if clickNum > historys.count {
                    historys .append(qst.logId)
                }
                tbv.reloadData()
            case M_SaveError:
                isShow = true
                errorCount += 1
                tbv.reloadData()
            case M_SavaTest:
                showMsg(msg: "考试结束：做了\(historys.count)题,错误\(errorCount)题")
            default:
                break
            }
           
            switch qtype {
            case 4:
                tnLbl.text = "\(clickNum)/100"
            default:
                tnLbl.text = "\(clickNum)/\(qst.total)"
            }
            
        }
        
    }
    @IBAction func toNextQuestion(_ sender: UIButton) {
        clickNum += 1
        getData()
    }
    @IBAction func toLastQuestion(_ sender: UIButton) {
        clickNum -= 1
        getData()
    }
    
    func toPostTest(){
        print("交卷")
        asyn_req_post(method: M_SavaTest, cb: self, p: ["testId":qst.testId as AnyObject,"errorQuestions":errorCount as AnyObject])
    }
    
    //MARK-按钮倒计时
    
    var countdownTimer: Timer?
    
    var remainingSeconds: Int = 0 {
        willSet {
           // conformBtn.setTitle("\(newValue/60)分\(newValue % 60)秒", for: .normal)
            conformBtn =  UIBarButtonItem(title: "\(newValue/60)分\(newValue % 60)秒", style: .plain, target: self, action: #selector(toPostTest))
            self.navigationItem.rightBarButtonItem = conformBtn
            if newValue <= 0 {
                isCounting = false
            }
        }
    }
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime(timer:)), userInfo: nil, repeats: true)
                
                remainingSeconds = 60*45
                
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                
            }
            
            conformBtn.isEnabled = !newValue
        }
    }
    
    
    func updateTime(timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值
        remainingSeconds -= 1
    }
}
